<?php
/**
 * Created by PhpStorm.
 * User: hebidu
 * Date: 15/7/3
 * Time: 09:29
 */

namespace Common\Api;

use Admin\Api\AuthGroupAccessApi;
use Admin\Api\MemberApi;
use Admin\Api\UidMgroupApi;
use Admin\Model\MgroupModel;
use Common\Model\WxuserGroupModel;
use Shop\Api\MemberConfigApi;
use Shop\Api\WalletApi;
use Uclient\Api\UserApi;
use Uclient\Model\UcenterMemberModel;

interface IAccount
{


    function login($username, $password,$type);

    function register($entity);

    function getInfo($id);

    function update($uid,$entity);


    function updatePwd($uid,$oldPwd,$newPwd);

}

/**
 * 本系统账号相关操作统一接口
 * Class AccountApi
 * @package Common\Api
 */
class AccountApi implements IAccount
{

    /**
     *  根据登录用户taobao_Openid获取用户信息
     */
    const GET_INFO_BY_SINA_WEIBO_OPENID = "Common/Account/getInfoBySinaWeiboOpenID";
    /**
     *  根据登录用户taobao_Openid获取用户信息
     */
    const GET_INFO_BY_TAOBAO_OPENID = "Common/Account/getInfoByTaobaoOpenID";
    /**
     *  根据登录用户QQ_Openid获取用户信息
     */
    const GET_INFO_BY_QQ_OPENID = "Common/Account/getInfoByQQOpenID";
    /**
     *  根据登录用户微信ID获取用户信息
     */
    const GET_INFO_BY_WXOPENID = "Common/Account/getInfoByWxOpenID";
    /**
     * 登录
     */
    const LOGIN = "Common/Account/login";
    /**
     * 注册
     */
    const REGISTER = "Common/Account/register";
    /**
     * 获取用户信息
     */
    const GET_INFO = "Common/Account/getInfo";

    const UPDATE="Common/Account/update";

    /**
     * 注册特定商家用户
     */
    const REGISTER_SPECIAL_STORE_USER = "Common/Account/registerSpecialStoreUser";

    /**
     * @param $uid 用户ID
     * @param $oldPwd 老密码
     * @param $newPwd 新密码
     */
    public function updatePwd($uid,$oldPwd,$newPwd){
        //根据用户ID查询用户

    }


    /**
     * 用户更新,不包括修改密码,可更新字段如下:
     * email
     * mobile
     * head
     * qq
     * sex
     * birthday
     * idnumber
     * nickname
     * realname
     * 存在$data
     */
    public function update($uid,$data){
//        $trans = M();
//        $trans->startTrans();
        $map=array(
        );

        if(isset($data['email'])){
            $map['email'] = $data['email'];
        }
        if(isset($data['mobile'])) {
            $map['mobile'] = $data['mobile'];
        }
        if(count($map) == 0){
            //无须更新
            $result['status'] = true;
        }else{
            $result= apiCall(UserApi::SAVE_BY_ID,array($uid,$map));
        }

        if($result['status']){
            $m=array(
              'uid'=>$uid
            );
            $map=array(
            );
            if(isset($data['head'])) {
                $map['head'] = $data['head'];
            }
            if(isset($data['qq'])) {
                $map['qq'] = $data['qq'];
            }
            if(isset($data['sex'])) {
                $map['sex'] = $data['sex'];
            }
            if(isset($data['birthday'])) {
                $map['birthday'] = $data['birthday'];
            }
            if(isset($data['idnumber'])) {
                $map['idnumber'] = $data['idnumber'];
            }
            if(isset($data['nickname'])){
                $map['nickname'] = $data['nickname'];
            }
            if(isset($data['realname'])) {
                $map['realname'] = $data['realname'];
            }

            $result= apiCall(MemberApi::SAVE,array($m,$map));

            if($result['status']){
//                $trans->commit();
                return array('status' => true, 'info' => $result['info']);
            }else{
//                $trans->rollback();
                return array('status' => false, 'info' => $result['info']);
            }
        }else{
            //$trans->rollback();
            return array('status' => false, 'info' => $result['info']);
        }
    }

    /**
     * 获得用户信息
     * @param $id
     * @return array
     */
    public function getInfo($id){


        $result = apiCall(UserApi::GET_INFO, array($id));

        if(!$result['status']){
            return array('status' => false, 'info' => $result['info']);
        }elseif(empty($result['info'])){
            return array('status' => false, 'info' => '未知错误code=1'.$id);
        }
        //1. 存储userApi里的
        $user_info = $result['info'];

        $result = apiCall(MemberApi::GET_INFO, array(array('uid'=>$id)));

        if(!$result['status']){
            return array('status' => false, 'info' => $result['info']);
        }elseif(empty($result['info'])){
            return array('status' => false, 'info' => '未知错误code=2'.$id);
        }

        $member_info = $result['info'];
        $result = apiCall(MemberConfigApi::GET_INFO, array(array('uid'=>$id)));

        if(!$result['status']){
            return array('status' => false, 'info' => $result['info']);
        }elseif(empty($result['info'])){
            return array('status' => false, 'info' => '未知错误code=3'.$id);
        }

        $member_config = $result['info'];

        $info = array_merge($user_info,$member_info,$member_config);

        $info = $this->convert($info);

        $info = $this->appendWalletInfo($info);

        return array('status'=>true,'info'=>$info);
    }


    private function appendWalletInfo($info){

        //1. 用户钱包信息
        $result = apiCall(WalletApi::GET_INFO_If_NOT_EXIST_THEN_ADD,array($info['uid']));

        if(!$result['status']){
            return array('status' => false, 'info' => $result['info']);
        }elseif(empty($result['info'])){
            return array('status' => false, 'info' => '未知错误code=4'.$id);
        }

        $info['coin'] = $result['info']['account_balance'];
        $info['frozencoin'] = $result['info']['frozen_funds'];

        return $info;
    }

    /**
     * 对用户信息进行转换
     * @param $user
     * @return mixed
     */
    private function convert($user){

        //1. 头像处理
        if((strpos($user['head'],"http") === 0)) {
            $user['head'] = htmlspecialchars_decode($user['head']);
            return $user;
        }
        $pic_id = intval($user['head']);

        if($pic_id > 0){
           $user['head'] = C('API_URL_OUT').'/Picture/index?id='.$pic_id;
        }

        //2. IP 转换
        $user['last_login_ip'] = long2ip($user['last_login_ip']);
        $user['reg_ip'] = long2ip($user['reg_ip']);

        return $user;

    }

    /**
     *
     * 获得用户信息,根据taobao_Openid
     * @param $openid
     * @return array
     */
    public function getInfoBySinaWeiboOpenID($openid){
        if(empty($openid)){
            return array('status' => false, 'info' => "openid无效");
        }
        $result = apiCall(MemberConfigApi::GET_INFO, array(array('sina_openid'=>$openid)));
        if(!$result['status']){
            return array('status' => false, 'info' => $result['info']);
        }elseif(empty($result['info'])){
            return array('status' => true, 'info' => '1.无法获取用户信息'.$id);
        }

        $id = $result['info']['uid'];

        $member_config = $result['info'];

        $result = apiCall(UserApi::GET_INFO, array($id));

        if(!$result['status']){
            return array('status' => false, 'info' => $result['info']);
        }elseif(empty($result['info'])){
            return array('status' => true, 'info' => '2.无法获取用户信息'.$id);
        }

        $user_info = $result['info'];

        $result = apiCall(MemberApi::GET_INFO, array(array('uid'=>$id)));

        if(!$result['status']){
            return array('status' => false, 'info' => $result['info']);
        }elseif(empty($result['info'])){
            return array('status' => true, 'info' => '3.无法获取用户信息'.$id);
        }

        $member_info = $result['info'];

        $info = array_merge($user_info,$member_info,$member_config);


        $info = $this->convert($info);

        $info = $this->appendWalletInfo($info);

        return array('status'=>true,'info'=>$info);
    }


    /**
     *
     * 获得用户信息,根据taobao_Openid
     * @param $openid
     * @return array
     */
    public function getInfoByTaobaoOpenID($openid){
        if(empty($openid)){
            return array('status' => false, 'info' => "openid无效");
        }
        $result = apiCall(MemberConfigApi::GET_INFO, array(array('taobao_openid'=>$openid)));
        if(!$result['status']){
            return array('status' => false, 'info' => $result['info']);
        }elseif(empty($result['info'])){
            return array('status' => true, 'info' => '1.无法获取用户信息'.$id);
        }

        $id = $result['info']['uid'];

        $member_config = $result['info'];

        $result = apiCall(UserApi::GET_INFO, array($id));

        if(!$result['status']){
            return array('status' => false, 'info' => $result['info']);
        }elseif(empty($result['info'])){
            return array('status' => true, 'info' => '2.无法获取用户信息'.$id);
        }

        $user_info = $result['info'];

        $result = apiCall(MemberApi::GET_INFO, array(array('uid'=>$id)));

        if(!$result['status']){
            return array('status' => false, 'info' => $result['info']);
        }elseif(empty($result['info'])){
            return array('status' => true, 'info' => '3.无法获取用户信息'.$id);
        }

        $member_info = $result['info'];

        $info = array_merge($user_info,$member_info,$member_config);


        $info = $this->convert($info);

        $info = $this->appendWalletInfo($info);

        return array('status'=>true,'info'=>$info);
    }

    /**
     *
     * 获得用户信息,根据QQ_Openid
     * @param $openid
     * @return array
     */
    public function getInfoByQQOpenID($openid){
        if(empty($openid)){
            return array('status' => false, 'info' => "openid无效");
        }
        $result = apiCall(MemberConfigApi::GET_INFO, array(array('qq_openid'=>$openid)));
        if(!$result['status']){
            return array('status' => false, 'info' => $result['info']);
        }elseif(empty($result['info'])){
            return array('status' => true, 'info' => '1.无法获取用户信息'.$id);
        }

        $id = $result['info']['uid'];

        $member_config = $result['info'];

        $result = apiCall(UserApi::GET_INFO, array($id));

        if(!$result['status']){
            return array('status' => false, 'info' => $result['info']);
        }elseif(empty($result['info'])){
            return array('status' => true, 'info' => '2.无法获取用户信息'.$id);
        }

        $user_info = $result['info'];

        $result = apiCall(MemberApi::GET_INFO, array(array('uid'=>$id)));

        if(!$result['status']){
            return array('status' => false, 'info' => $result['info']);
        }elseif(empty($result['info'])){
            return array('status' => true, 'info' => '3.无法获取用户信息'.$id);
        }

        $member_info = $result['info'];

        $info = array_merge($user_info,$member_info,$member_config);

        $info = $this->convert($info);

        $info = $this->appendWalletInfo($info);

        return array('status'=>true,'info'=>$info);
    }

    /**
     * 获得用户信息
     * @param $id
     * @return array
     */
    public function getInfoByWxOpenID($openid){

        $result = apiCall(MemberConfigApi::GET_INFO, array(array('wxopenid'=>$openid)));
        if(!$result['status']){
            return array('status' => false, 'info' => $result['info']);
        }elseif(empty($result['info'])){
            return array('status' => true, 'info' => '1.无法获取用户信息'.$id);
        }

        $id = $result['info']['uid'];

        $member_config = $result['info'];

        $result = apiCall(UserApi::GET_INFO, array($id));

        if(!$result['status']){
            return array('status' => false, 'info' => $result['info']);
        }elseif(empty($result['info'])){
            return array('status' => true, 'info' => '2.无法获取用户信息'.$id);
        }

        $user_info = $result['info'];

        $result = apiCall(MemberApi::GET_INFO, array(array('uid'=>$id)));

        if(!$result['status']){
            return array('status' => false, 'info' => $result['info']);
        }elseif(empty($result['info'])){
            return array('status' => true, 'info' => '3.无法获取用户信息'.$id);
        }

        $member_info = $result['info'];

        $info = array_merge($user_info,$member_info,$member_config);


        $info = $this->convert($info);

        $info = $this->appendWalletInfo($info);

        return array('status'=>true,'info'=>$info);
    }

    public function login($username, $password,$type)
    {
        $result=apiCall(UserApi::LOGIN,array($username, $password,$type));
        return $result;
    }

    /**
     * 注册特定商家用户
     * $entity ＝ array(
        'username'=>'用户名',
        'password'=>'密码明文'
        'email'=>'用户邮箱'
        'role'=>'用户所属角色'
        'add_uid'=>'添加该用户的用户ID'
     * );
     * @author hebiduhebi@126.com
     * @param $entity
     * @return array
     */
    public function registerSpecialStoreUser($entity){

        $username = $entity['username'];
        $password = $entity['password'];
        $email  = $entity['email'];
        $role  = $entity['role'];
        $add_uid  = $entity['add_uid'];
        $error = false;
        /* 调用注册接口注册用户 */
        $result = apiCall(UserApi::REGISTER, array($username, $password, $email));

        if($result['status']){ //注册成功
            //1. 开启事务
            $trans = M();
            $trans->startTrans();
            $uid = $result['info'];

            $entity = array(
                'uid'=>$uid,
                'nickname'=>$username,
                'realname'=>'',
                'idnumber'=>'',
                'add_uid'=>$add_uid
            );
            $result = apiCall(MemberApi::ADD, array($entity));
            if(!$result['status']){
                $error = "用户添加失败";
            } else {

                $result = apiCall(AuthGroupAccessApi::ADD_TO_GROUP,array($uid,$role));

                if(!$result['status']){
                    $error = $result['info'];
                }

            }

            if($error === false){
                $trans->commit();
                return array('status' => true, 'info' => $uid);
            }else{

                $trans->rollback();
                //1. 因为UserApi用的数据库链接不一样，所以要单独删除
                $result = apiCall(UserApi::DELETE_BY_ID, array($uid));
                return array('status' => false, 'info' => $error);
            }
        } else { //注册失败，显示错误信息
            return array('status' => false, 'info' => $result['info']);
        }

    }


    /**
     *
     * @param $entity | key＝》username,password ,from,     .realname,email,mobile非必须
     *  type,
     *  username
     *  password,
     *  email,
     *  mobile,
     *  from,realname,nickname,birthday,idcode,head,sex
     * @return array
     */
        public function register($entity)
    {
        if (!isset($entity['username']) || !isset($entity['password']) || !isset($entity['from'])) {
            return array('status' => false, 'info' => "账户信息缺失!");
        }

        if(!isset($entity['idcode'])){
            return array('status'=>false,'info'=>"缺失IDCODE");
        }
        $type     = $entity['type'];
        $username = $entity['username'];
//        $test_username = str_replace($username;
        if(strlen($username) < 6 || strlen($username) > 64){
            return array('status'=>false,'info'=>'用户名的长度必须大于6小于64');
        }
        if(!preg_match("/^[a-zA-Z]{1}[a-zA-Z0-9_]{5,64}$/",$username)){
            return array('status'=>false,'info'=>'账户名必须为字母、数字或下划线的组合且第一个必须为字母!');
        }
        $password = $entity['password'];
        if(strlen($password) < 6 || strlen($password) > 64){
            return array('status'=>false,'info'=>'密码的长度必须大于6小于64');
        }
        if(!preg_match("/^[0-9a-zA-Z\\\\,.?><;:!@#$%^&*()_+-=\[\]\{\}\|]{6,64}$/",$password)){
            return array('status'=>false,'info'=>'密码只能包含数字、英文字母以及如下字符 \,.?><;:!@#$%^&*()_+-=!');
        }
        $invite_id = !empty($entity['invite_id'])?$entity['invite_id']:'';
        $mobile = !empty($entity['mobile'])?$entity['mobile']:'';
        $email = !empty($entity['email'])?$entity['email']:'';
        $from  = !empty($entity['from'])?$entity['from']:'';
        $realname  = !empty($entity['realname'])?$entity['realname']:'';
        $nickname  = !empty($entity['nickname'])?$entity['nickname']:'';
        $birthday = !empty($entity['birthday'])?$entity['birthday']:'';
        $idcode = !empty($entity['idcode'])?$entity['idcode']:'';
        $head = !empty($entity['head'])?$entity['head']:'';
        $sex = !empty($entity['sex'])?$entity['sex']:"";
        $weixin_bind = !empty($entity['weixin_bind'])?$entity['weixin_bind']:0;
        //微信的openid
        $wxopenid  = !empty($entity['wxopenid'])?$entity['wxopenid']:'';
        //QQ的openid
        $qq_openid  = !empty($entity['qq_openid'])?$entity['qq_openid']:'';
        //Taobao的openid
        $taobao_openid  = !empty($entity['taobao_openid'])?$entity['taobao_openid']:'';
        //新浪微博的openid
        $sina_openid  = !empty($entity['sina_openid'])?$entity['sina_openid']:'';

        $creator_uid = !empty($entity['creator_uid'])?$entity['creator_uid']:0;

        $trans = M();
        $trans->startTrans();
        $error = "";
        $flag = false;
        $result = apiCall(UserApi::REGISTER, array($username, $password, $email, $mobile, $from));
        $uid = 0;

        if ($result['status']) {
            $uid = $result['info'];
            $member = array(
                'uid' => $uid,
                'realname' => $realname,
                'nickname' => $nickname,
                'idnumber' => '',
                'sex' =>  $sex,
                'birthday' => $birthday,
                'qq' => '',
                'head'=>$head,
                'score' => 0,
                'login' => 0,
            );

            $result = apiCall(MemberApi::ADD, array($member));

            if (!$result['status']) {
                $flag = true;
                $error = '[用户信息]'.$result['info'];
            }else{

            }
        } else {
            $flag = true;
            $error = '[用户账户]'.$result['info'];
        }

        if(!$flag){

            //插入到第三张表
            $map=array(
                'uid'=>$uid,
                'phone_validate'=>0,
                'email_validate'=>0,
                //'weixin_bind'=>$weixin_bind,
                'idcode'=>$idcode,
                'wxopenid'=>$wxopenid,
                'identity_validate'=>0,
                'invite_id' => $invite_id,
                /**
                 * 增加qq登录
                 *
                 * @author hebidu <hebiduhebi@126.com>
                 * @date  15/11/26 11:26
                 * @copyright by itboye.com
                 */
                //'qq_openid'=>$qq_openid,
                /**
                 *
                 * 增加淘宝登录
                 * @author hebidu <hebiduhebi@126.com>
                 * @date  15/11/27 09:25
                 * @copyright by itboye.com
                 */
                //'taobao_openid'=>$taobao_openid,
                /**
                 *
                 * 新浪微博
                 * @author hebidu <hebiduhebi@126.com>
                 * @date  15/11/27 13:47
                 * @copyright by itboye.com  
                 */ 
                //'sina_openid'=>$sina_openid,
            );

            if($type == UcenterMemberModel::ACCOUNT_TYPE_MOBILE) {
                $map['phone_validate'] = 1;
            }

            $result = apiCall(MemberConfigApi::ADD,array($map));
            if(!$result['status'] ){
                $flag = true;
                $error = '[用户配置]'.$result['info'];
            }

        }


        /*if(!$flag){

            //插入到第四张表
            $entity = array(
                'uid'=>$uid,
                'groupid'=>MgroupModel::DEFAULT_GROUP,
                'creator_uid'=>$creator_uid,
                'createtime'=>time(),
            );

            $result = apiCall(UidMgroupApi::ADD,array($entity));
            if(!$result['status']){
                $error = '[用户组]'.$result['info'];
                return array('status' => false, 'info' => $error);
            }

        }*/

        if ($flag) {
            $result = apiCall(UserApi::DELETE_BY_ID, array($uid));
            $trans->rollback();

            return array('status' => false, 'info' => $error);
        } else {
            $trans->commit();
            /**
             *
             * 增加idcode 的处理，idcode ＝ 用户uid+100000的36进制表示
             * @author hebidu <hebiduhebi@126.com>
             * @date  15/11/29 17:11
             * @copyright by itboye.com  
             */
            $idcode = get_36HEX($uid+100000);
            $result = apiCall(MemberConfigApi::SAVE_BY_ID,array($uid,array('idcode'=>$idcode)));

            return array('status' => true, 'info' => $uid);
        }

    }

}